package com.app.island.cash.requestwork

import com.app.island.cash.data.sigle.LogoutEvent
import com.app.island.cash.data.sigle.UpdateEvent
import com.app.island.cash.utilstools.NetWorkLoadingUtil
import com.app.island.cash.utilstools.ToastUtil
import com.orhanobut.logger.Logger
import org.greenrobot.eventbus.EventBus
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response

abstract class RequestCallBack<T> : Callback<T> {
    override fun onResponse(call: Call<T>, response: Response<T>) {
        NetWorkLoadingUtil.dismissDialog()
        if (response.isSuccessful && response.body() is HttpResult<*>) {
            val result = response.body() as HttpResult<*>?
            if (result?.code == 200) {
                onSuccess(response.body())
            } else {
                onError(result?.code!!, result.msg!!)
            }
        }
    }

    open fun onError(code: Int, msg: String) {
        if (code == 414) {
            EventBus.getDefault().post(UpdateEvent(msg))
        } else if (code == 410 || code == 411 || code == 412 || code == 413) {
            EventBus.getDefault().post(LogoutEvent(msg!!))
        } else {
            ToastUtil.toast(msg)
        }
    }

    abstract fun onSuccess(body: T?)
    override fun onFailure(call: Call<T>, t: Throwable) {
        t.printStackTrace()
        NetWorkLoadingUtil.dismissDialog()
        ToastUtil.toast("Network error,please check your network")
    }
}